<?php
namespace Tbf\Bundle\PackageBundle\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;

/**
 * 上tag管理
 */
class PackageTagCompilerPass implements CompilerPassInterface
{
    /**
     * You can modify the container here before it is dumped to PHP code.
     *
     * @param ContainerBuilder $container
     *
     * @api
     */
    public function process(ContainerBuilder $container)
    {
        $package_list = $container->findTaggedServiceIds(
            'tbf_package'
        );
        $manager_definition = $container->getDefinition('tbf_package.manager');
        foreach ($package_list as $service_id=>$attributes) {
            $definition = $container->getDefinition($service_id);
            $class_name = $definition->getClass();

            $package = new $class_name();
            $package->compilerPass($container);

            $manager_definition->addMethodCall(
                'addPackage',
                array(new Reference($service_id))
            );
        }

        $container_list = $container->findTaggedServiceIds(
            'tbf_package_controller'
        );
        $manager_definition = $container->getDefinition('tbf_package.manager');
        foreach ($container_list as $service_id=>$attributes) {
            $definition = $container->getDefinition($service_id);
            $definition->addMethodCall(
                'setControllerServiceId',
                array($service_id)
            );
            $manager_definition->addMethodCall(
                'addControllerConfig',
                array(new Reference($service_id))
            );
        }
        //var_export($container->getDefinition('doctrine.orm.default_metadata_driver')->getMethodCalls());

        /*

                foreach ($package_list as $service_id=>$attributes) {
                    $dispatcher = $container->getDefinition($dispatcher_id);
                    if (!empty($dispatcher_attributes[0]['subscriber_tag'])) {
                        $subscriber_tag_name =  $dispatcher_attributes[0]['subscriber_tag'];
                    } else {
                        $subscriber_tag_name =   $dispatcher_id.'.subscriber';
                    }
                    $subscriber_list = $container->findTaggedServiceIds(
                        $subscriber_tag_name
                    );
                    foreach ($subscriber_list as $subscriber_id=>$subscriber_attributes) {
                        $dispatcher->addMethodCall(
                            'addSubscriber',
                            array(new Reference($subscriber_id))
                        );
                    }
                }
        */
    }
}
